<template>
  <div class="container">
    <!-- 分类导航栏 -->
    <ul class="cat_list w">
      <li v-for="(item, index) in topCateList" :key="index" class="cat_box" :class="isCateSelected===index?'selected':''" @click="handleChangeCate(index, item.cat_id)">
        <img :src="item.cat_icon" class="cat_icon">
        <h3 class="cat_title">{{ item.cat_name }}</h3>
        <!-- 标题下方的三角形 -->
        <div class="tri"></div>
      </li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters } from 'vuex'
export default {
  name: 'CateNav',
  computed: {
    ...mapState(['isCateSelected']),
    ...mapGetters(['topCateList'])
  },
  methods: {
    ...mapMutations(['changeCate']),
    // 点击切换一级分类
    handleChangeCate (index, id) {
      const obj = {
        index,
        id
      }
      this.changeCate(obj)
      // 滑动滚动条
      if (index > 1) {
        document.querySelector('.cat_list').scrollLeft = document.querySelectorAll('.cat_box')[index].offsetLeft - 150
      } else {
        document.querySelector('.cat_list').scrollLeft = 0
      }
    }
  },
  mounted () {
    const routeObj = {
      index: parseInt(this.$route.params.id) - 1,
      id: parseInt(this.$route.params.id)
    }
    this.changeCate(routeObj)
    // 滑动滚动条
    if (routeObj.index > 1) {
      document.querySelector('.cat_list').scrollLeft = document.querySelectorAll('.cat_box')[routeObj.index].offsetLeft - 150
    } else {
      document.querySelector('.cat_list').scrollLeft = 0
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  padding-top: .4rem;
}
// 分类导航栏
.cat_list {
  overflow-x: scroll;
  overflow-y: hidden;
    &::-webkit-scrollbar {
      display: none;
    }
  width: 100%;
  white-space: nowrap;
}
.cat_box {
  position: relative;
  display: inline-block;
  width: 3rem;
  height: 3.5rem;
  color: #333;
  padding: 0 0.2rem;
  text-align: center;
}
.cat_icon {
  display: inline-block;
  box-sizing: border-box;
  width: 2rem;
  height: 2rem;
  border-radius: 1rem;
  padding: .2rem;
  border: 1px solid transparent;
  margin-bottom: .2rem;
}
.cat_title {
  display: block;
  height: .6rem;
  font-size: .56rem;
  padding: 0 .24rem;
  border-radius: 3rem;
}
.tri {
  position: absolute;
  bottom: 0;
  left: 50%;
  margin-left: -0.4rem;
  border: .4rem solid transparent;
}
// 点击标题后的样式
.selected {
  .cat_icon {
    border: 1px solid rgb(255, 20, 147);
  }
  .cat_title {
    color: #fff;
    background-color: rgb(255, 20, 147);
  }
  // 标题下方的三角形
  .tri {
    border-bottom: .4rem solid #fff;
  }
}
</style>
